
package member

import (
    "time"
    "errors"
    "strings"
    "dhfshop/models"
	"github.com/astaxie/beego/orm"
	"dhfshop/models/consts"
)

// 余额日志表
type BalanceLog struct {
	Id           int64   `orm:"column(id);pk;auto" json:"id" form:"id"` 
	PartnerId    int64   `orm:"column(partner_id)" json:"partner_id" form:"partner_id"`
    StoreId      int64   `orm:"column(store_id)" json:"store_id" form:"store_id"`                 /* 店铺ID */
	MemberId     int64   `orm:"column(member_id)" json:"member_id" form:"member_id"`              // 会员编号
	OuterNo      string  `orm:"column(outer_no);size(190);index" json:"outer_no" form:"outer_no"` // 订单号 
	InOutType    int8    `orm:"column(in_out_type)" json:"in_out_type" form:"in_out_type"`        /*收支类型: 0支出,1收入*/
	BusinessKind int     `orm:"column(kind)" json:"kind" form:"kind"`                             /*业务类型*/
	Title        string  `orm:"column(title);size(256);null" json:"title" form:"title"`           // 
	SrcBalance   float32 `orm:"column(src_balance);digits(12);decimals(2)" json:"src_balance" form:"src_balance"`  /* 修改前余额*/
	IncBalance   float32 `orm:"column(inc_balance);digits(12);decimals(2)" json:"inc_balance" form:"inc_balance"`  /* 余额变动量*/
	DstBalance   float32 `orm:"column(dst_balance);digits(12);decimals(2)" json:"dst_balance" form:"dst_balance"`  /* 修改后余额*/
	SrcPresent   float32 `orm:"column(src_present);digits(12);decimals(2)" json:"src_present" form:"src_present"`  /* 修改前赠送额*/
	IncPresent   float32 `orm:"column(inc_present);digits(12);decimals(2)" json:"inc_present" form:"inc_present"`  /* 赠送额变动量*/
	DstPresent   float32 `orm:"column(dst_present);digits(12);decimals(2)" json:"dst_present" form:"dst_present"`  /* 修改后赠送额*/
	//
	Present      float32 `orm:"column(present);digits(12);decimals(2)" json:"present" form:"present"` /*本次赠送额*/
	RelateUser   int64   `orm:"column(rel_user)" json:"rel_user" form:"rel_user"`                     /*关联操作人,仅在客服操作时,记录操作人*/
	State        int     `orm:"column(state);default(0)" json:"state" form:"state"`                   /*状态：0是未支付，1支付成功*/
	Remark       string  `orm:"column(remark);size(256);null" json:"remark" form:"remark"`            //备注        
    CreatedAt  time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-" form:"-"`     //创建时间
	CreatedAtStr string  `orm:"-" json:"created_at,omitempty" form:"-"`
	CouponFee    float32 `orm:"column(coupon_fee);digits(12);decimals(2)" json:"coupon_fee" form:"coupon_fee"` /*代金券或立减优惠金额*/
}

func init() {
    orm.RegisterModel(new(BalanceLog))   
}

// 保存余额日志记录
func AddBalanceLog(m *BalanceLog) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetBalanceLogByOuterNo(outerNo string) (logs *BalanceLog, err error) {
	o := models.GetDefaultDB()
	logs = &BalanceLog{OuterNo: outerNo}  
	if err = o.Read(logs, "OuterNo"); err != nil {
		return
	}
	return
}

func GetBalanceLogByMemberId(memberId int64) (logs *BalanceLog, err error) {
	o := models.GetDefaultDB()
	logs = &BalanceLog{MemberId: memberId}  
	if err = o.Read(logs, "MemberId"); err != nil {
		return
	}
	return
}

func GetBalanceLogByOutOuterNo(outerNo string) (logs *BalanceLog, err error) {
	o := models.GetDefaultDB()
	logs = &BalanceLog{InOutType: 0, OuterNo: outerNo}  
	if err = o.Read(logs, "InOutType", "OuterNo"); err != nil {
		return
	}
	return
}

// 查询余额日志记录
func GetAllBalanceLogs(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*BalanceLog,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(BalanceLog))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {   //in order to: in
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*BalanceLog
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		for _, log := range lists {
			log.CreatedAtStr = log.CreatedAt.Format(consts.DATETIME_FORMAT)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateBalanceLogById(m *BalanceLog, k ...string) (err error) {
	o := models.GetDefaultDB()
	v := BalanceLog{Id: m.Id}
	if err = o.Read(&v); err != nil {
		return err
	}else{
	    if _, err = o.Update(m, k...); err != nil {
		   return err
		}
	}
	return nil
}

// 更新代金券或立减优惠金额
func UpdateBalanceLogCouponFee(m *BalanceLog) (err error) {
	err = UpdateBalanceLogById(m, "coupon_fee")
	return
}
